# -*- coding: utf-8 -*-
from __future__ import print_function
import os, sys, pdb, shutil
import time
import logging
import hashlib
import zipfile
from user.models import FileStore
from software.forms import softwareVersion_check, dataId_check, file_check
from django.http import JsonResponse
from software.models import SoftwareData, SoftwareVersion
from order.views.createOrder import random_str, orderNum
from conf.sysConfig import config
from user.dataCheck import DataCheck
from user.dataCheck import randomNumber
from software.views.view_download import FastDFSStorage
from pprint import pprint

datacheck = DataCheck()
tmpDir = os.path.join(config["dataDir"], config["tmpDir"])
ifUseFastDFS = config["isUseFastDFS"]
logger_request = logging.getLogger("django.request")


# 保存文件至数据库
def saveToDatabase(fileName, user, filePath, fileType=0, uniqueFile="uniqueFile"):
    size = os.path.getsize(filePath)
    # logger_request.info("*************************")
    # logger_request.info(filePath)
    # logger_request.info(type(filePath))
    # logger_request.info("*************************")
    if ifUseFastDFS:
        fastDFS = FastDFSStorage()
        _, msg = fastDFS._save(filePath)
        if _:
            dfsPath = msg + "?filename=" + fileName
        else:
            dfsPath = ""
    else:
        dfsPath = ""

    fileStore = FileStore.objects.create(
        owner=user,
        fileName=fileName,
        fileType=fileType,
        filePath=filePath,
        size=size_format(size),
        uniqueFile=uniqueFile,
        dfsPath=dfsPath
    )
    return fileStore.id


# 将编组文件打包并存储
def tarSaveToDataBase(idDict, token):
    try:
        """
            idDict = {
                '软件版本id'： {
                    'softwareName': 'softwareName',
                    'DataID': {
                        'dataId': {'fileName': '', 'filePath': 'filePath'  }
                        'dataId': {'fileName': '', 'filePath': 'filePath'  }
                        'dataId': {'fileName': '', 'filePath': 'filePath'  }
                    },
                    'FileID': {
                        'fileId': {'fileName': '', 'filePath': 'filePath'  }
                        'fileId': {'fileName': '', 'filePath': 'filePath'  }
                        'fileId': {'fileName': '', 'filePath': 'filePath'  }
                    }
                }
            }
        """
        user = datacheck.getUser(token)
        str = orderNum()[:12] + random_str(6)
        rootDir = mkDirs(os.path.join(tmpDir, str))
        for i in idDict.items():
            softwareVersion_check(i[0])
            pprint(i)
            # softwareVersion = SoftwareVersion.objects.filter(pk=i)
            # softwareVersionItem = softwareVersion[0]
            softwareName = idDict[i[0]]['softwareName']
            softwareDir = mkDirs(os.path.join(rootDir, softwareName))
            for f in i[1]['FileID'].items():
                # pdb.set_trace()
                file_check(f[0])
                softwareVersionFilePath = f[1]['filePath']
                softwareVersionFileName = f[1]['fileName']
                copy(softwareVersionFilePath, os.path.join(softwareDir, softwareVersionFileName))
            # pdb.set_trace()
            for d in i[1]['DataID'].items():
                file_check(d[0])
                dataName = random_str(4) + i[1]['DataID'][d[0]]['fileName']
                dataPath = i[1]['DataID'][d[0]]['filePath']
                # print(dataName)
                copy(dataPath, os.path.join(softwareDir, dataName))
        zipDir = zip_yasuo(rootDir)
        # make_zip(rootDir, str)
        # zipDir = os.path.join(tmpDir, str)
        fileId = saveToDatabase(str + '.zip', user=user, filePath=zipDir, fileType=2,
                                uniqueFile=getLocalToken())
        shutil.rmtree(rootDir)

    except Exception as e:
        code = 1
        msg = e
        return code, msg, []
    code = 0
    msg = 'success'
    return code, msg, [str + '.zip', zipDir]


def mkDirs(path):
    if not os.path.exists(path):
        os.makedirs(path)
    else:
        pass
    return path


def copy(oldPath, newPathDir):
    shutil.copy(oldPath, newPathDir)


# 打包目录为zip文件（未压缩）
def make_zip(source_dir, output_filename):
    zipf = zipfile.ZipFile(output_filename, 'w')
    pre_len = len(os.path.dirname(source_dir))
    for parent, dirnames, filenames in os.walk(source_dir):
        for filename in filenames:
            pathfile = os.path.join(parent, filename)
            arcname = pathfile[pre_len:].strip(os.path.sep)  # 相对路径
            zipf.write(pathfile, arcname)
    zipf.close()


def zip_yasuo(start_dir):
    file_news = start_dir + '.zip'
    z = zipfile.ZipFile(file_news, 'w', zipfile.ZIP_DEFLATED)
    for dir_path, dir_names, file_names in os.walk(start_dir):
        file_path = dir_path.replace(start_dir, '')
        file_path = file_path and file_path + os.sep or ''
        for filename in file_names:
            z.write(os.path.join(dir_path, filename), file_path + filename)
    z.close()
    return file_news


def size_format(size):
    if size < 1000:
        return '%.lf' % size + 'B'
    elif 1024 <= size < 1048576:
        return '%.1f' % float(size / 1024) + 'KB'
    elif 1048576 <= size < 1073741824:
        return '%.1f' % float(size / 1048576) + 'MB'
    elif 1073741824 <= size < 1099511627776:
        return '%.1f' % float(size / 1073741824) + 'GB'
    elif 1099511627776 <= size:
        return '%.1f' % float(size / 1099511627776) + 'TB'


def getLocalToken():
    timeStamp = time.time()
    localTime = time.localtime(timeStamp)
    strTime = time.strftime("%Y%m%d%H", localTime)
    str = randomNumber(30)
    hl = hashlib.md5()
    hl.update(str.encode(encoding='utf-8'))
    return hl.hexdigest()[0:20]
